package cn.stu.framework.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.stu.common.utils.ApiData;
import cn.stu.framework.entity.Attendance;
import cn.stu.framework.mapper.AttendanceMapper;
import cn.stu.framework.service.AttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * 实施考勤服务
 *
 * @author 郑志豪
 * @date 2023/09/18
 */
@Service
public class AttendanceServiceImpl implements AttendanceService {
    /**
     * 出勤映射器
     */
    @Autowired
    private AttendanceMapper attendanceMapper;


    /**
     * 按用户ID和时钟日期列出
     *
     * @param year   年
     * @param month  月份
     * @param day    天
     * @param userId 用户ID
     * @return {@link ApiData}
     */
    @Override
    @Cacheable(value = "attendanceList", key = "'userId:'+#userId+':'+#year+':'+#month+':'+#day", sync = true)
    public ApiData listByUserIdAndClockDate(Integer year, Integer month, Integer day, Long userId) {
        List<Attendance> attendances = attendanceMapper.listByUserIdAndClockDate(userId, year, month, day);
        return ApiData.getTrue("获取成功", attendances);
    }

    /**
     * 创建
     *
     * @param userId 用户ID
     * @return {@link ApiData}
     */
    @Override
    @CacheEvict(value = "attendanceList", key = "'userId:'+#userId", allEntries = true, beforeInvocation = true)
    public ApiData create(Long userId) {
        LocalDateTime nowDateTime = LocalDateTime.now();
        int year = nowDateTime.getYear();
        int month = nowDateTime.getMonthValue();
        int day = nowDateTime.getDayOfMonth();
        List<Attendance> list = attendanceMapper.listByUserIdAndClockDate(userId, year, month, day);
        if (CollUtil.isNotEmpty(list)) {
            return ApiData.getFalse("时间异常");
        }
        Attendance add = new Attendance();
        add.setUserId(userId);
        String workingHoursStart = attendanceMapper.selectSettingValueByName("working_hours_start");
        Duration duration = Duration.between(LocalTime.parse(workingHoursStart), LocalTime.now());
        long lateMinutes = duration.toMinutes();
        if (lateMinutes > 0) {
            add.setComeLateMinutes((int) lateMinutes);
        }
        add.setClockDate(LocalDate.now());
        add.setClockInTime(LocalTime.now());
        attendanceMapper.insert(add);
        return ApiData.getTrue("签到成功", add);
    }

    /**
     * 更新
     *
     * @param id     ID
     * @param userId 用户ID
     * @return {@link ApiData}
     */
    @Override
    @CacheEvict(value = "attendanceList", key = "'userId:'+#userId", allEntries = true, beforeInvocation = true)
    public ApiData update(Long id, Long userId) {
        Attendance atte = attendanceMapper.selectById(id);
        if (atte == null) {
            return ApiData.getFalse("");
        }
        if (atte.getClockOutTime() != null) {
            return ApiData.getFalse("");
        }
        String workingHoursEnd = attendanceMapper.selectSettingValueByName("working_hours_end");
        Duration duration = Duration.between(LocalTime.now(), LocalTime.parse(workingHoursEnd));
        long earlyMinutes = duration.toMinutes();
        if (earlyMinutes > 0) {
            atte.setLeaveEarlyMinutes((int) earlyMinutes);
        }
        atte.setClockOutTime(LocalTime.now());
        attendanceMapper.updateById(atte);
        return ApiData.getTrue("签退成功！", atte);
    }
}